// pkg/jwt/jwt.go
package jwt

import (
	"github.com/golang-jwt/jwt/v4" // 使用v4版本
	"time"
)

type JWTService interface {
	GenerateToken(userID uint) (string, error)
	ValidateToken(tokenString string) (*jwt.Token, error)
}

type jwtService struct {
	secret  string
	timeout int
}

func NewJWTService(secret string, timeout int) JWTService {
	return &jwtService{
		secret:  secret,
		timeout: timeout,
	}
}

func (s *jwtService) GenerateToken(userID uint) (string, error) {
	claims := jwt.MapClaims{
		"user_id": userID,
		"exp":     time.Now().Add(time.Second * time.Duration(s.timeout)).Unix(),
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(s.secret))
}

func (s *jwtService) ValidateToken(tokenString string) (*jwt.Token, error) {
	return jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, jwt.ErrSignatureInvalid
		}
		return []byte(s.secret), nil
	})
}